﻿using System;
using System.Collections.Generic;
using System.Text;
using com.tiyma.common;
using com.tiyma.components;
using System.Web;
using System.Text.RegularExpressions;
using com.tiyma.model;

namespace com.tiyma.components
{
    /// <summary>
    /// 章节内容搜索管理类
    /// </summary>
    public class ChapterContentManager
    {
        /// <summary>
        /// 匹配章节内容正在
        /// </summary>
        private string m_chapter_content_reg = "<(?=div|table|td)[^>]*?(?=booktext|bookcontent|readtxt)[^<>]*?>";

        /// <summary>
        /// 匹配html标签
        /// </summary>
        private string m_html_tag_reg = "<[/]*(?=div|table|td)[^<>]*?>";

        /// <summary>
        /// 章节图片的正则
        /// </summary>
        private string m_img_reg = "<img[^<>]*?src=s*[\'\"]*([^\"\']*\\d+/\\d+/\\d+[^\"\']*)[\'\"]*[^<>]*?>";

        /// <summary>
        /// 百度关键字列表正则
        /// </summary>
        private string m_key_url_reg = "<h3\\s*?class=[\'\"]?t[\'\"]?><a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h3>";

        /// <summary>
        /// soos关键字正则
        /// </summary>
        private string m_soso_url_reg="<h3>\\s*?<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h3>";



        BookManager m_db_mgr = new BookManager();

        /// <summary>
        /// 是否后台运行
        /// </summary>
        private bool m_is_back_ground_run = false;
        public bool IsBackGroundRun
        {
            get
            {
                return m_is_back_ground_run;
            }
            set
            {
                m_is_back_ground_run = value;
            }
        }


        /// <summary>
        /// 搜索普通章节
        /// </summary>
        /// <param name="i_script"></param>
        /// <returns></returns>
        public string SEONChapter(string i_script)
        {
            if (string.IsNullOrEmpty(i_script))
                return "参数错误";

            i_script = DESEncryptBYTriple.Decrypt(i_script);

            string[] t_arr = i_script.Split(new char[] { '$' }, StringSplitOptions.None);

            if (t_arr == null || t_arr.Length != 6)
                return "参数错误";

            string t_book_id = t_arr[0];
            string t_chapter_id = t_arr[1];
            string t_site_id = t_arr[2];
            string t_chapter_url = t_arr[3];
            string t_book_name = t_arr[4];
            string t_chapter_name = t_arr[5];

            ChapterInfo t_chapter = new ChapterInfo();
            t_chapter.BookId = t_book_id;
            t_chapter.ChapterId = t_chapter_id;
            t_chapter.ChapterUrl = t_chapter_url;

            BookChapterManager t_chapter_mgr = new BookChapterManager();

            string t_chapter_content = string.Empty;

            //纵横小说直接走百度搜索引擎，其他小说去小说站点收录普通章节
            if (t_site_id != Consts.zongheng.ToString())
            {
                t_chapter_content= t_chapter_mgr.SearchNomalChapter(t_chapter, Convert.ToInt32(t_site_id));
            }

            //普通章节未找到，通过关键字去百度搜索
            if (string.IsNullOrEmpty(t_chapter_content) || SystemUtil.GetStringLength(t_chapter_content) < 300)
            {
                int t_start_index = 0;
                string t_start_sign = string.Empty;
                string t_end_sign = string.Empty;
                string t_chapter_list_url = string.Empty;

                t_chapter_content = SearchChapterContent(
                    t_book_name,
                    t_chapter_name,
                   Convert.ToInt64( t_book_id),
                   Convert.ToInt64( t_chapter_id),
                    out t_start_index,
                    out t_start_sign,
                    out t_end_sign,
                    out t_chapter_url,
                    out t_chapter_list_url);

                if (!string.IsNullOrEmpty(t_chapter_list_url))
                {
                    BookUrlInfo t_book_url = new BookUrlInfo();
                    t_book_url.BookId =Convert.ToInt64( t_book_id);
                    t_book_url.ChapterListUrl = t_chapter_list_url;
                    t_book_url.Host = new Uri(t_chapter_list_url).Host;
                    t_book_url.Bits = 1;
                    t_book_url.SartIndex = t_start_index;
                    t_book_url.StartSign = t_start_sign;
                    t_book_url.EndSign = t_end_sign;

                    m_db_mgr.AddBookUrl(t_book_url);
                }

               
            }
    
            if (string.IsNullOrEmpty(t_chapter_content))
            {
                string t_search_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(string.Format("{0} {1}", t_book_name, t_chapter_name)));
                t_chapter_content = string.Format("抱歉搜索到章节内容，互联网相关章节内容还没有提供，你可以<a href='{0}' target='_blank'>点击这里到互联网上看看其他相关网站是否有更新!</a><br>我们会尽快收录，感谢你的关注<br>", t_search_url);
            }

            if (!string.IsNullOrEmpty(t_chapter_content))
            {
                t_chapter_content = SystemUtil.JsonCharFilter(t_chapter_content);

            }

            return t_chapter_content;
        }


        /// <summary>
        /// 搜索章节内容
        /// </summary>
        /// <param name="i_script"></param>
        /// <returns></returns>
        public string SEOChapter(string i_script)
        {
            if (string.IsNullOrEmpty(i_script))
            {
                return "参数错误";
            }

            i_script = DESEncryptBYTriple.Decrypt(i_script);

            string[] t_arr = i_script.Split(new char[] { '$' }, StringSplitOptions.None);

            if (t_arr == null || t_arr.Length != 4)
                return "参数错误";
            //关键字
            string t_book_name = t_arr[0];
            string t_chapter_name = t_arr[1];
            long t_book_id = 0;
            long t_chapter_id = 0;

            if (!long.TryParse(t_arr[2], out t_book_id))
                t_book_id = 0;
            if (!long.TryParse(t_arr[3], out t_chapter_id))
                t_chapter_id = 0;

            string t_chapter_content=string.Empty;

            int t_start_index = 0;
            string t_start_sign = string.Empty;
            string t_end_sign = string.Empty;
            string t_chapter_url = string.Empty;
            string t_chapter_list_url = string.Empty;

            t_chapter_content = SearchChapterContent(
                     t_book_name,
                     t_chapter_name,
                     t_book_id,
                     t_chapter_id,
                     out t_start_index,
                     out t_start_sign,
                     out t_end_sign,
                     out t_chapter_url,
                     out t_chapter_list_url);

            if (!string.IsNullOrEmpty(t_chapter_list_url))
            {
                BookUrlInfo t_book_url = new BookUrlInfo();
                t_book_url.BookId = t_book_id;
                t_book_url.ChapterListUrl = t_chapter_list_url;
                t_book_url.Host = new Uri(t_chapter_list_url).Host;
                t_book_url.Bits = 1;
                t_book_url.SartIndex = t_start_index;
                t_book_url.StartSign = t_start_sign;
                t_book_url.EndSign = t_end_sign;

                m_db_mgr.AddBookUrl(t_book_url);
            }

            if (!string.IsNullOrEmpty(t_chapter_content))
            {
                t_chapter_content = SystemUtil.JsonCharFilter(t_chapter_content);

                return t_chapter_content;
            }
            

            List<BookUrlInfo> t_book_url_list = m_db_mgr.GetBookUrlByBookId(t_book_id);

            List<BookUrlInfo> t_url_list = t_book_url_list.FindAll(delegate(BookUrlInfo t_url)
            {
                return string.IsNullOrEmpty(t_url.StartSign) == false;
            });

            if (t_url_list == null || t_url_list.Count == 0)
            {

                string t_search_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(string.Format("{0} {1}", t_book_name, t_chapter_name)));
                t_chapter_content = string.Format("抱歉搜索到章节内容，互联网相关章节内容还没有提供，你可以<a href='{0}' target='_blank'>点击这里到互联网上看看其他相关网站是否有更新!</a><br>我们会尽快收录，感谢你的关注<br>", t_search_url);
                return t_chapter_content;

            }
            else
            {

                foreach (BookUrlInfo t_url in t_url_list)
                {
                   List<ChapterInfo>  t_normal_chapter_list = GetChapterByDBUrl(t_url.ChapterListUrl);

                   if (t_normal_chapter_list == null || t_normal_chapter_list.Count == 0)
                       continue;

                   foreach (ChapterInfo t_normal_chapter in t_normal_chapter_list)
                   {
                       if (NetSiteCatchManager.CompareChapterName(t_chapter_name, t_normal_chapter.ChapterName) == true)
                       {
                           //从百度去搜索章节内容
                           t_chapter_content = GetContentBySign(t_book_id, t_chapter_id,
                               t_normal_chapter.ChapterUrl, t_url.SartIndex, t_url.StartSign, t_url.EndSign);

                           break;
                       }
                      
                   }

                   if (!string.IsNullOrEmpty(t_chapter_content))
                       break;

                }
            }

            if (string.IsNullOrEmpty(t_chapter_content))
            {
                string t_search_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(string.Format("{0} {1}",t_book_name,t_chapter_name)));
                t_chapter_content = string.Format("抱歉搜索到章节内容，互联网相关章节内容还没有提供，你可以<a href='{0}' target='_blank'>点击这里到互联网上看看其他相关网站是否有更新!</a><br>我们会尽快收录，感谢你的关注<br>", t_search_url);
            }

            t_chapter_content = SystemUtil.JsonCharFilter(t_chapter_content);

            return t_chapter_content;


        }


        /// <summary>
        /// 获取章节列表
        /// </summary>
        /// <param name="i_chapter_list_url"></param>
        /// <returns></returns>
        private List<ChapterInfo> GetChapterByDBUrl(string i_chapter_list_url)
        {
            if (string.IsNullOrEmpty(i_chapter_list_url))
                return null;

            try
            {
                string t_html = HttpHelper.GetHttpRequestStringByNUll_Post(i_chapter_list_url);

                if (string.IsNullOrEmpty(t_html))
                    return null;

                MatchCollection t_ma = Regex.Matches(t_html, "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>([^<>]*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_ma == null || t_ma.Count <= 0)
                    return null;

                List<ChapterInfo> t_chapter_list = new List<ChapterInfo>();

                foreach (Match t_mc in t_ma)
                {

                    ChapterInfo t_chapter = new ChapterInfo();

                    t_chapter.ChapterUrl = NetSiteCatchManager.GetFullUrl(i_chapter_list_url, t_mc.Groups[1].Value.ToString());
                    t_chapter.ChapterName = t_mc.Groups[2].Value.ToString();
                    t_chapter_list.Add(t_chapter);

                }

                return t_chapter_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节列表失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 搜索小说章节内容
        /// </summary>
        /// <param name="i_book_name">小说名称</param>
        /// <param name="i_chapter_name">章节名称</param>
        /// <param name="i_book_id">小说ID</param>
        /// <param name="i_chapter_id">章节ID</param>
        /// <param name="o_chapter_url">搜索到的章节地址</param>
        /// <param name="o_chatper_list_url">搜索到的章节列表地址（可能为空）</param>
        /// <returns></returns>
        public string SearchChapterContent(string i_book_name, string i_chapter_name, long i_book_id, long i_chapter_id, out int o_start_index,
            out string o_start_sign, out string o_end_sign, out string o_chapter_url, out string o_chatper_list_url)
        {
            o_start_index = 0;
            o_chapter_url = string.Empty;
            o_chatper_list_url = string.Empty;
            o_start_sign = string.Empty;
            o_end_sign = string.Empty;

            //百度搜索更新的站点
            string t_search_url = string.Format("http://www.soso.com/q?pid=s.idx&cid=s.idx.se&w={0}", HttpUtility.UrlEncode(string.Format("{0} {1}", i_book_name, i_chapter_name)));

            //搜索到的结果
            string t_chapter_content = string.Empty;

            try
            {
                //得到页面源代码
                string t_html = HttpHelper.GetHttpRequestStringByNUll_Post(t_search_url);
                //没获取到页面内容
                if (string.IsNullOrEmpty(t_html)) return t_chapter_content;

                //解析关键字url列表
                MatchCollection t_ma = Regex.Matches(t_html, m_soso_url_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                //没有列表
                if (t_ma == null || t_ma.Count == 0)
                {
                    LogHelper.Info(string.Format("soso获取关键字：{0} {1} 没得到列表，可能是正则有问题.", i_book_name, i_chapter_name));
                    return t_chapter_content;
                }

                int t_index = 0;

                string t_chapter_url = string.Empty;

                foreach (Match t_mc in t_ma)
                {
                    if (t_mc.Groups.Count == 3)
                    {
                        t_chapter_url = t_mc.Groups[1].Value.ToString();

                        //如果地址是被禁止的
                        if (NetSiteCatchManager.IsPiraticSite(t_chapter_url) == false)
                            continue;

                        t_chapter_content = GetChapterContent(i_chapter_name, i_book_id, i_chapter_id, t_chapter_url, out o_chatper_list_url, out o_start_index,
                            out o_start_sign, out o_end_sign, true);
                        //找到了章节内容
                        if (!string.IsNullOrEmpty(t_chapter_content))
                        {
                            break;
                        }

                        t_index++;

                        //不是后台运行，之需要收录三页
                        if (m_is_back_ground_run == false)
                        {
                            if (t_index == 3)
                                break;
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                LogHelper.Error("百度搜索关键字失败" + ex.ToString());
            }

            return t_chapter_content;
        }

        /// <summary>
        /// 获取章节内容
        /// </summary>
        /// <param name="i_chapter_name">章节名称</param>
        /// <param name="i_chapter_url">章节地址</param>
        /// <param name="o_chatper_list_url">章节地址列表</param>
        /// <param name="o_tart_sign">解析章节内容的开始标记</param>
        /// <param name="o_end_sign">解析章节内容的结束标记</param>
        /// <param name="i_check">是否检查章节内容的长度</param>
        /// <returns></returns>
        public string GetChapterContent(string i_chapter_name, long i_book_id, long i_chapter_id,
            string i_chapter_url, out string o_chatper_list_url, out int o_start_index, out string o_start_sign, out string o_end_sign, bool i_check)
        {

            o_chatper_list_url = string.Empty;
            o_end_sign = string.Empty;
            o_start_sign = string.Empty;
            o_start_index = 0;

            string t_chapter_content = ParseContentByUrl(i_chapter_name, i_chapter_url, out o_chatper_list_url, out o_start_index, out o_start_sign, out o_end_sign, i_check);

            //找到了章节内容
            if (!string.IsNullOrEmpty(t_chapter_content))
            {
                t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);

                if (string.IsNullOrEmpty(t_chapter_content))
                    return string.Empty;

            }

            MatchCollection t_img_ma = Regex.Matches(t_chapter_content, m_img_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_img_ma != null && t_img_ma.Count > 8)
            {
                t_chapter_content = Regex.Replace(t_chapter_content, "<img.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                t_img_ma = null;
            }

            //后台运行的话，如果章节内容是图片，把图片下载到本地
            if (m_is_back_ground_run)
            {
               
                if (t_img_ma != null && t_img_ma.Count > 0)
                {
                    StringBuilder t_sb = new StringBuilder();

                    foreach (Match t_img_mc in t_img_ma)
                    {
                        //下载图片
                        string t_file_name = NetSiteCatchManager.DownLoadFile(
                            t_img_mc.Groups[1].Value.ToString(),
                           AppConfig.ChapterPath, i_book_id, i_chapter_id);

                        //下载成功
                        if (!string.IsNullOrEmpty(t_file_name) && t_file_name != "noimg")
                        {
                            t_sb.AppendFormat("<img src=\"{0}\" border=\"0\" /><br><br>", t_file_name);

                        }
                        else
                        {
                            t_sb.AppendFormat("<img src=\"{0}\" border=\"0\" /><br><br>", NetSiteCatchManager.GetFullUrl(i_chapter_url, t_img_mc.Groups[1].Value.ToString()));
                        }
                    }

                    t_chapter_content = t_sb.ToString();
                }
            }

            //保存章节内容
            bool t_save_ret = NetSiteCatchManager.WriteBookContent(
                AppConfig.ChapterRoot, i_book_id, i_chapter_id, t_chapter_content);

            //更新章节下载状态
            if (t_save_ret)
            {
                BookUrlInfo t_book_url = new BookUrlInfo();
                t_book_url.ChapterListUrl = o_chatper_list_url;
                t_book_url.SartIndex = o_start_index;
                t_book_url.StartSign = o_start_sign;
                t_book_url.EndSign = o_end_sign;
                m_db_mgr.UpdateChapter(i_book_id, i_chapter_id, i_chapter_url, t_book_url);

            }

            return t_chapter_content;

        }

        /// <summary>
        /// 从某个地址去解析页面章节内容
        /// </summary>
        /// <param name="i_chapter_name"></param>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_id"></param>
        /// <param name="o_chapter_url"></param>
        /// <param name="o_chatper_list_url"></param>
        /// <returns></returns>
        private string ParseContentByUrl(string i_chapter_name, string i_chapter_url, out string o_chatper_list_url,
            out int o_start_index, out string o_start_sign, out string o_end_sign, bool i_check)
        {
            o_start_index = 0;
            o_chatper_list_url = string.Empty;
            o_start_sign = string.Empty;
            o_end_sign = string.Empty;

            string t_chapter_content = string.Empty;

            try
            {
                //获取页面源代码
                string t_html = HttpHelper.GetHttpRequestStringByNUll_Post(i_chapter_url);
                //没获取到页面代码或者返回404
                if (string.IsNullOrEmpty(t_html) || t_html == "404") return string.Empty;

                //先查找小说章节列表地址
                Match t_url_list_mc = Regex.Match(t_html, "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>[^<>]*?目录[^<>]*?</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_url_list_mc == null || t_url_list_mc.Groups.Count == 0 || string.IsNullOrEmpty(t_url_list_mc.Groups[1].Value.ToString()))
                {
                    t_url_list_mc = Regex.Match(t_html, "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>[^<>]*?书目[^<>]*?</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_url_list_mc == null || t_url_list_mc.Groups.Count == 0 || string.IsNullOrEmpty(t_url_list_mc.Groups[1].Value.ToString()))
                    {
                        t_url_list_mc = Regex.Match(t_html, "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>[^<>]*?列表[^<>]*?</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                }

                if (t_url_list_mc != null && t_url_list_mc.Groups.Count > 0)
                {
                    o_chatper_list_url = t_url_list_mc.Groups[1].Value.ToString();

                    if (!string.IsNullOrEmpty(o_chatper_list_url))
                    {
                        o_chatper_list_url = NetSiteCatchManager.GetFullUrl(i_chapter_url, o_chatper_list_url);
                    }
                }

                //判断小说章节title是否包含章节名称
                Match t_mc = Regex.Match(t_html, "<[^<>]*?title[^<>]*?>(.*?)</title[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_mc != null && t_mc.Groups.Count > 0)
                {
                    string t_chapter_name = t_mc.Groups[1].Value.ToString();
                    if (NetSiteCatchManager.CompareChapterName(i_chapter_name, t_chapter_name) == false)
                        return string.Empty;
                }

                //如果小说章节是图片
                MatchCollection t_img_ma = Regex.Matches(t_html, m_img_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_img_ma != null && t_img_ma.Count > 0 && t_img_ma.Count <= 5)
                {
                    StringBuilder t_img_sb = new StringBuilder();

                    foreach (Match t_img_mc in t_img_ma)
                    {
                        t_img_sb.AppendFormat("<img src='{0}' border='0' /><br>", NetSiteCatchManager.GetFullUrl(i_chapter_url, t_img_mc.Groups[1].Value.ToString()));
                    }

                    return t_img_sb.ToString();
                }

                //如果页面章节内容有分页
                MatchCollection t_ma = Regex.Matches(t_html, "<a[^<>]*?href=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>\\S{0,2}(\\d+)\\S{0,2}</a>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if ((t_ma != null) && (t_ma.Count > 0))
                {
                    StringBuilder t_sb = new StringBuilder();

                    string t_current_chapter_content  = GetContentByPerPage(t_html, i_chapter_url, out o_start_index, out o_start_sign, out o_end_sign, false);

                    t_current_chapter_content = NetSiteCatchManager.ReplaceContent(t_current_chapter_content);

                    if (string.IsNullOrEmpty(t_current_chapter_content))
                        return string.Empty;

                    int t_page_index = 0;
                    int t_max_page_index = 0;
                    int t_current_page_index = 1;

                    for (int index = 1; index < t_ma.Count; index++)
                    {
                        if (!int.TryParse(t_ma[index].Groups[2].Value.ToString(), out t_page_index))
                            continue;

                        if (NetSiteCatchManager.GetFullUrl(i_chapter_url, t_ma[index].Groups[1].Value.ToString()).ToLower() == i_chapter_url.ToLower())
                        {
                            t_current_page_index = t_page_index;
                        }

                        if (t_page_index > t_max_page_index)
                            t_max_page_index = t_page_index;

                    }

                    if (t_current_page_index == 1)
                    {
                        Match t_page_index_mc=Regex.Match(i_chapter_url,"[-_]+(\\d+)\\.",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                        if (t_page_index_mc != null && t_page_index_mc.Groups.Count > 0)
                        {
                            if (!int.TryParse(t_page_index_mc.Groups[1].Value.ToString(), out t_current_page_index))
                                t_current_page_index = 1;
                        }
                    }

                    if (t_current_page_index > t_max_page_index)
                        t_max_page_index = t_current_page_index;

                    int t_page = 0;

                    for (t_page_index = 1; t_page_index <= t_max_page_index; t_page_index++)
                    {
                        if (t_page_index == t_current_page_index)
                        {
                            t_sb.Append(t_current_chapter_content);
                            t_sb.Append("<br><br>");
                            continue;
                        }

                        for (int index = 0; index < t_ma.Count; index++)
                        {
                            if (!int.TryParse(t_ma[index].Groups[2].Value.ToString(), out t_page))
                                continue;

                            if (t_page_index == t_page)
                            {

                                string t_url = NetSiteCatchManager.GetFullUrl(i_chapter_url, t_ma[index].Groups[1].Value.ToString());

                                if (!Regex.IsMatch(t_url, "http://[^/]+/\\S+/\\S+", RegexOptions.IgnoreCase))
                                    break;

                                t_html = HttpHelper.GetHttpRequestStringByNUll_Post(t_url);

                                t_chapter_content = GetContentByPerPage(t_html, i_chapter_url, out o_start_index, out o_start_sign, out o_end_sign, false);

                                t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);

                                if (string.IsNullOrEmpty(t_chapter_content))
                                {
                                    break;
                                }
                                else
                                {
                                    t_sb.Append(t_chapter_content);
                                    t_sb.Append("<br><br>");
                                }
                                break;
                            }
                        }

                    }

                    return t_sb.ToString();
                }

                t_chapter_content = GetContentByPerPage(t_html, i_chapter_url, out o_start_index, out o_start_sign, out o_end_sign, i_check);

                return t_chapter_content;


            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("从地址：{0} 搜索小说章节内容出现异常:{1}", i_chapter_url, ex.ToString()));
                return string.Empty;
            }

        }

        /// <summary>
        /// 解析页面的章节信息
        /// </summary>
        /// <param name="i_html"></param>
        /// <param name="i_chapter_url"></param>
        /// <param name="i_check">如果章节页面信息是分页信息传false否则传true</param>
        /// <returns></returns>
        private string GetContentByPerPage(string i_html, string i_chapter_url, out int o_start_index, out string o_start_sign, out string o_end_sign, bool i_check)
        {
            o_start_index = 0;
            o_start_sign = string.Empty;
            o_end_sign = string.Empty;

            string t_chapter_content = string.Empty;

            string t_sub_content = string.Empty;

            string t_temp_html = string.Empty;

            MatchCollection t_ma_c = Regex.Matches(i_html, m_chapter_content_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);

            if (t_ma_c == null || t_ma_c.Count == 0)
            {
                t_ma_c = Regex.Matches(i_html, m_html_tag_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                t_chapter_content = GetContentByReg(t_ma_c, i_chapter_url, i_html, out o_start_index, out o_start_sign, out o_end_sign, i_check);
            }
            else
            {

                string t_start_sign = string.Empty;
                string t_end_sign = string.Empty;

                for (int index = t_ma_c.Count - 1; index >= 0; index--)
                {
                    t_temp_html = i_html.Substring(t_ma_c[index].Index);

                    t_sub_content = GetContentByHTML(t_temp_html, i_chapter_url, i_check);

                    if (t_sub_content.Length > t_chapter_content.Length)
                    {
                        o_start_index = t_ma_c[index].Index;
                        o_start_sign = t_ma_c[index].Groups[0].Value;
                        MatchCollection t_tag_ma = Regex.Matches(t_sub_content, m_html_tag_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        if (t_tag_ma != null && t_tag_ma.Count > 0)
                        {
                            o_end_sign = t_tag_ma[t_tag_ma.Count - 1].Groups[0].Value.ToString();
                        }

                        t_chapter_content = t_sub_content;
                    }
                }
            }

            return t_chapter_content;


        }

        /// <summary>
        /// 通过解析内容获取章节内容信息
        /// </summary>
        /// <param name="i_html"></param>
        /// <param name="i_chapter_url"></param>
        /// <param name="i_check"></param>
        /// <returns></returns>
        private string GetContentByHTML(string i_html, string i_chapter_url, bool i_check)
        {


            if (string.IsNullOrEmpty(i_html))
                return string.Empty;

            i_html = FilterContent(i_html);

            bool t_is_img = false;

            StringBuilder t_sb = new StringBuilder();

            //替换坏的图片
            MatchCollection t_bad_img_ma = Regex.Matches(i_html, "<img[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_bad_img_ma != null && t_bad_img_ma.Count > 8)
            {
                i_html = Regex.Replace(i_html, "<img[^<>]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }

            //如果小说章节是图片
            MatchCollection t_img_ma = Regex.Matches(i_html, m_img_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);

            if (t_img_ma != null && t_img_ma.Count > 0 && t_img_ma.Count <= 5)
            {

                foreach (Match t_img_mc in t_img_ma)
                {
                    t_sb.AppendFormat("<img src='{0}' border='0' /><br>", NetSiteCatchManager.GetFullUrl(i_chapter_url, t_img_mc.Groups[1].Value.ToString()));
                }
                t_is_img = true;
            }

            if (t_is_img)
                return t_sb.ToString();

            string t_temp_conent = Regex.Replace(i_html, "<a[^<>]*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            t_temp_conent = Regex.Replace(t_temp_conent, "[\\【】\\s\\d_：。&:|（）a-zA-Z，！？(),!?;\\.；、……<>=\"\'/]", "", RegexOptions.IgnoreCase);
           

            if (i_check)
            {
                if (string.IsNullOrEmpty(t_temp_conent) || t_temp_conent.Length < 1000)
                    return string.Empty;
            }
            else
            {
                if (string.IsNullOrEmpty(t_temp_conent) || t_temp_conent.Length < 50 || i_html.ToLower().IndexOf("copyright")>-1 || i_html.IndexOf("本站")>-1)
                    return string.Empty;
            }

            return i_html;
        }

        /// <summary>
        /// 获取标签于标签之间的内容
        /// </summary>
        /// <param name="i_content"></param>
        /// <returns></returns>
        private string FilterContent(string i_content)
        {
            if (string.IsNullOrEmpty(i_content))
                return string.Empty;

            MatchCollection t_ma = Regex.Matches(i_content, m_html_tag_reg, RegexOptions.IgnoreCase);

            if (t_ma == null || t_ma.Count == 0)
                return string.Empty;

            Stack<string> t_tack = new Stack<string>();

            foreach (Match t_c in t_ma)
            {
                if (t_c.Groups[0].Value.Contains("/")) //结束标签，弹出栈
                {
                    if (t_c.Index <= 0)
                        continue;

                    if (t_tack.Count == 0) //如果栈为空，找到了成对的闭合标签
                    {

                        i_content = i_content.Substring(0, t_c.Index + t_c.Groups[0].Value.ToString().Length);
                        break;
                    }
                    else
                    {
                        t_tack.Pop();
                        if (t_tack.Count == 0)
                        {
                            i_content = i_content.Substring(0, t_c.Index + t_c.Groups[0].Value.ToString().Length);
                            break;
                        }
                    }
                }
                else //非闭合标签 压入栈
                {
                    t_tack.Push(t_c.Groups[0].Value.ToString());
                }
            }

            return i_content;
        }

        /// <summary>
        /// 获取标记
        /// </summary>
        /// <param name="i_html"></param>
        /// <param name="i_type">1为开始标记 2 为结束标记</param>
        /// <returns></returns>
        private string GetSign(string i_html, int i_type, out int o_start_index)
        {
            o_start_index = 0;

            string t_sign = string.Empty;

            MatchCollection t_ma = Regex.Matches(i_html, m_html_tag_reg, RegexOptions.IgnoreCase);

            if (t_ma == null || t_ma.Count == 0)
                return string.Empty;

            if (i_type == 1) //获取开始标记 从后往前遍历
            {

                t_sign = t_ma[t_ma.Count - 1].Groups[0].Value.ToString();
                o_start_index = i_html.LastIndexOf(t_sign);
            }
            else if (i_type == 2)
            {

                t_sign = t_ma[0].Groups[0].Value.ToString();
            }

            return t_sign;
        }

        /// <summary>
        /// 获取标签与标签之间的章节内容
        /// </summary>
        /// <param name="i_ma">标签结合</param>
        /// <param name="i_chapter_url">章节地址</param>
        /// <param name="i_html">章节内容</param>
        /// <param name="o_start_index">章节内容开始位置</param>
        /// <param name="o_start_sign">章节内容开始标记</param>
        /// <param name="o_end_sign">章节内容结束标记</param>
        /// <param name="i_check">是否检查章节内容长度</param>
        /// <returns></returns>
        private string GetContentByReg(MatchCollection i_ma, string i_chapter_url, string i_html, out int o_start_index, out string o_start_sign, out string o_end_sign, bool i_check)
        {
            o_start_index = 0;
            o_start_sign = string.Empty;
            o_end_sign = string.Empty;

            StringBuilder t_sb = new StringBuilder();

            string t_content = string.Empty;

            string t_sub_content = string.Empty;

            string t_temp_content = string.Empty;

            bool t_is_img = false;

            if ((i_ma != null) && (i_ma.Count > 0))
            {
                for (int i = 0; i < (i_ma.Count - 1); i++)
                {

                    t_sub_content = i_html.Substring(i_ma[i].Index, i_ma[i + 1].Index - i_ma[i].Index);

                    //替换坏的图片
                    MatchCollection t_bad_img_ma = Regex.Matches(t_sub_content, "<img[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_bad_img_ma != null && t_bad_img_ma.Count > 8)
                    {
                        t_sub_content = Regex.Replace(t_sub_content, "<img[^<>]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }

                    //如果小说章节是图片
                    MatchCollection t_img_ma = Regex.Matches(t_sub_content, m_img_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_img_ma != null && t_img_ma.Count > 0 && t_img_ma.Count <= 5)
                    {
                        o_start_sign = GetSign(i_html.Substring(0, i_ma[i].Index + i_ma[i].Groups[0].Value.ToString().Length), 1, out o_start_index);
                        int t_temp_index = 0;
                        o_end_sign = GetSign(i_html.Substring(i_ma[i + 1].Index - i_ma[i + 1].Groups[0].Value.ToString().Length), 2, out t_temp_index);

                        foreach (Match t_img_mc in t_img_ma)
                        {
                            t_sb.AppendFormat("<img src='{0}' border='0' /><br>", NetSiteCatchManager.GetFullUrl(i_chapter_url, t_img_mc.Groups[1].Value.ToString()));
                        }
                        t_is_img = true;
                        continue;
                    }

                    if (!string.IsNullOrEmpty(t_sub_content))
                    {
                        t_temp_content = Regex.Replace(t_sub_content, "<a[^<>]*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        t_temp_content = Regex.Replace(t_temp_content, "[\\【】\\s\\d_：。&|:（）a-zA-Z，！？(),!?;\\.；、……<>=\"\'/]", "", RegexOptions.IgnoreCase);
                        if (t_temp_content.Length > 50 && t_sub_content.ToLower().IndexOf("copyright")<0 && t_sub_content.IndexOf("本站")<0)
                        {
                            o_start_sign = GetSign(i_html.Substring(0, i_ma[i].Index + i_ma[i].Groups[0].Value.ToString().Length), 1, out o_start_index);
                            int t_temp_index = 0;
                            o_end_sign = GetSign(i_html.Substring(i_ma[i + 1].Index - i_ma[i + 1].Groups[0].Value.ToString().Length), 2, out t_temp_index);

                            t_sb.Append(t_sub_content);
                        }
                    }
                }


            }

            if (t_is_img)
                return t_sb.ToString();

            t_content = t_sb.ToString();

            if (i_check)
            {
                if (t_content.Length > 1000)
                {
                    return t_content;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(t_content) && t_content.Length > 50)
                {
                    return t_content;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取章节内容
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_chapter_url"></param>
        /// <param name="i_start_index"></param>
        /// <param name="i_start_sign"></param>
        /// <param name="i_end_sign"></param>
        /// <returns></returns>
        public string GetContentBySign(long i_book_id, long i_chapter_id, string i_chapter_url, int i_start_index, string i_start_sign, string i_end_sign)
        {

            try
            {
                string t_html = HttpHelper.GetHttpRequestStringByNUll_Post(i_chapter_url);

                StringBuilder t_sb = new StringBuilder();

                string t_chapter_content = GetContentBySignWithHtml(i_book_id, i_chapter_id, t_html, i_chapter_url, i_start_index, i_start_sign, i_end_sign);

                if (string.IsNullOrEmpty(t_chapter_content))
                    return string.Empty;

                t_sb.Append(t_chapter_content);

                //如果页面章节内容有分页
                MatchCollection t_ma = Regex.Matches(t_html, "<a[^<>]*?href=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>\\S{0,2}(\\d+)\\S{0,2}</a>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if ((t_ma != null) && (t_ma.Count > 0))
                {
                    t_sb.Append("<br><br>");

                    int t_page_index = 0;
                    int t_max_page_index = 0;

                    for (int index = 1; index < t_ma.Count; index++)
                    {
                        if (!int.TryParse(t_ma[index].Groups[2].Value.ToString(), out t_page_index))
                            continue;

                        if (t_page_index > t_max_page_index)
                            t_max_page_index = t_page_index;

                    }

                    int t_page = 0;

                    for (t_page_index = 2; t_page_index <= t_max_page_index; t_page_index++)
                    {

                        for (int index = 0; index < t_ma.Count; index++)
                        {
                            if (!int.TryParse(t_ma[index].Groups[2].Value.ToString(), out t_page))
                                continue;

                            if (t_page == t_page_index)
                            {

                                string t_url = NetSiteCatchManager.GetFullUrl(i_chapter_url, t_ma[index].Groups[1].Value.ToString());

                                if (!Regex.IsMatch(t_url, "http://[^/]+/\\S+/\\S+", RegexOptions.IgnoreCase))
                                    break;

                                t_html = HttpHelper.GetHttpRequestStringByNUll_Post(t_url);

                                t_chapter_content = GetContentBySignWithHtml(i_book_id, i_chapter_id, t_html, i_chapter_url, i_start_index, i_start_sign, i_end_sign);

                                if (string.IsNullOrEmpty(t_chapter_content))
                                {
                                    break;
                                }
                                else
                                {
                                    t_sb.Append(t_chapter_content);
                                    t_sb.Append("<br><br>");
                                }
                                break;
                            }

                        }
                    }

                }

                t_chapter_content = t_sb.ToString();

                //找到了章节内容
                if (!string.IsNullOrEmpty(t_chapter_content))
                {
                    t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);

                    if (string.IsNullOrEmpty(t_chapter_content))
                        return string.Empty;


                }

                MatchCollection t_img_ma = Regex.Matches(t_chapter_content, m_img_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_img_ma.Count > 8)
                {
                    t_chapter_content = Regex.Replace(t_chapter_content, "<img.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    t_img_ma = null;

                }

              

                //保存章节内容
                bool t_save_ret = NetSiteCatchManager.WriteBookContent(
                   AppConfig.ChapterRoot, i_book_id, i_chapter_id, t_chapter_content);

                //更新章节下载状态
                if (t_save_ret)
                {
                    BookUrlInfo t_book_url = new BookUrlInfo();
                    t_book_url.ChapterListUrl = "";
                    t_book_url.SartIndex = 0;
                    m_db_mgr.UpdateChapter(i_book_id, i_chapter_id, i_chapter_url, t_book_url);

                }

                return t_chapter_content;

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节内容失败" + ex.ToString());
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取章节内容
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_chapter_url"></param>
        /// <param name="i_start_index"></param>
        /// <param name="i_start_sign"></param>
        /// <param name="i_end_sign"></param>
        /// <returns></returns>
        public string GetContentBySignWithHtml(long i_book_id, long i_chapter_id, string i_html, string i_chapter_url, int i_start_index, string i_start_sign, string i_end_sign)
        {

            try
            {
                MatchCollection t_start_ma = Regex.Matches(i_html, i_start_sign, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                MatchCollection t_end_ma = Regex.Matches(i_html, i_end_sign, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                string t_chapter_content = string.Empty;

                if (t_start_ma != null && t_start_ma.Count > 0 && t_end_ma != null && t_end_ma.Count > 0)
                {
                    t_chapter_content = i_html.Substring(t_start_ma[t_start_ma.Count - 1].Index, (t_end_ma[t_end_ma.Count - 1].Index - t_start_ma[t_start_ma.Count - 1].Index));

                    if (!string.IsNullOrEmpty(t_chapter_content))
                        t_chapter_content = FilterContent(t_chapter_content);
                }
                else
                {
                    t_chapter_content = GetContentByPerPage(i_html, i_chapter_url, out i_start_index, out i_start_sign, out i_end_sign, false);
                    t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);

                }


                return t_chapter_content;

            }
            catch (Exception ex)
            {
                LogHelper.Error("根据标记获取小说章节内容失败" + ex.ToString());
                return string.Empty;
            }
        }


    }
}
